<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 主体搜索和添加功能 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-button
            type="primary"
            @click="dialogCtrl = true"
          >添加用户</el-button>
        </el-col>
        <el-col :span="12">
          <el-input
            placeholder="请输入内容"
            v-model="userQuery.query"
            clearable
            @clear="getUserList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            ></el-button>
          </el-input>
        </el-col>
      </el-row>

      <!-- 渲染用户列表区域 -->
      <el-table
        :data="userList"
        stripe
        border
      >
        <el-table-column type="index"></el-table-column>
        <el-table-column
          label="姓名"
          prop="username"
        ></el-table-column>
        <el-table-column
          label="邮箱"
          prop="email"
        ></el-table-column>
        <el-table-column
          label="电话"
          prop="mobile"
        ></el-table-column>
        <el-table-column
          label="权限"
          prop="role_name"
        ></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="state">
            <el-switch
              v-model="state.row.mg_state"
              @change="changeState(state.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          width="180px"
        >
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showDialogEdit(scope.row.id)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="delUserInfo(scope.row.id)"
            ></el-button>
            <el-tooltip
              effect="dark"
              content="角色权限"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="setRole(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 显示分页  -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="userQuery.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="userQuery.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>

    </el-card>

    <!-- 这是添加用户按钮点击后会弹起来的面板 -->
    <el-dialog
      title="添加用户"
      :visible.sync="dialogCtrl"
      width="50%"
      @close="dialogClose"
    >
      <!-- 主体 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="70px"
      >
        <el-form-item
          label="用户名"
          prop="username"
        >
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item
          label="密码"
          prop="password"
        >
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item
          label="邮箱"
          prop="email"
        >
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item
          label="手机号"
          prop="mobile"
        >
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>

      <!-- 控制 -->
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="dialogCtrl = false">取 消</el-button>
        <el-button
          type="primary"
          @click="addUser"
        >确 定</el-button>
      </span>
    </el-dialog>

    <!-- 这是修改用户按钮点击后会弹起来的面板 -->
    <el-dialog
      title="修改用户"
      :visible.sync="dialogEdit"
      width="50%"
    >

      <!-- 主体 -->
      <el-form
        :model="editForm"
        :rules="addFormRules"
        ref="editFormRef"
        label-width="70px"
      >
        <el-form-item label="用户名">
          <el-input
            v-model="editForm.username"
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item
          label="邮箱"
          prop="email"
        >
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item
          label="手机号"
          prop="mobile"
        >
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>

      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="dialogEdit = false">取 消</el-button>
        <el-button
          type="primary"
          @click="resetUserInfo"
        >确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色面板 -->
    <el-dialog
      title="提示"
      :visible.sync="setRoleDialog"
      width="50%"
    >

      <!-- 显示用户的信息 -->
      <div>
        <p>用户名称: {{ roleObj.username }}</p>
        <p>用户角色: {{ roleObj.role_name }}</p>
        <p>分配新角色:

          <el-select
            v-model="setRoleId"
            placeholder="请选择"
          >
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :value="item.id"
              :label="item.roleName"
            ></el-option>
          </el-select>

        </p>
      </div>

      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="setRoleDialog = false">取 消</el-button>
        <el-button
          type="primary"
          @click="saveRole(roleObj.id)"
        >确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
export default {
  data() {
    // 自定义邮箱的匹配规则
    let checkEmail = (rule, val, cb) => {
      // 创建邮箱的正则对象
      const emailExp = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/
      // 验证如果通过，则调用回调函数，不要忘了return，不继续往下执行
      if (emailExp.test(val)) return cb()
      // 如果校验不通过，则返回一个 Error 的实例，输入报错信息
      cb(new Error('你看看你的邮箱是个什么玩意儿'))
    }
    let checkMobile = (rule, val, cb) => {
      const emailExp = /^1([38][0-9]|4[5-9]|5[0-3,5-9]|66|7[0-8]|9[89])[0-9]{8}$/
      if (emailExp.test(val)) return cb()
      cb(new Error('你的手机号坏了，看看吧'))
    }
    return {
      userQuery: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      userList: [],
      total: 0,
      dialogCtrl: false,
      // 数据总控
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 规则总控
      addFormRules: {
        username: [
          { required: true, message: '用户名必须输入', trigger: 'blur' },
          { min: 3, max: 8, message: '用户名长度在3-8位', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '密码必须输入', trigger: 'blur' },
          { min: 6, max: 12, message: '密码长度在6-12位', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '邮箱必须输入', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '手机号必须输入', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      dialogEdit: false,
      editForm: {},
      // 设置角色的显示值
      setRoleDialog: false,
      // 设置角色对象需要用到的值
      roleObj: {},
      // 所有角色列表的数组
      roleList: [],
      // 设置下拉框中临时存储的值
      setRoleId: ''
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    // 获取用户列表数据
    async getUserList() {
      let { data: res } = await this.$http.get('users', {
        params: this.userQuery
      })
      this.userList = res.data.users
      this.total = res.data.total
    },
    // 切换每页显示的总条数，会触发函数获得每页最大的数值
    handleSizeChange(sizesVal) {
      this.userQuery.pagesize = sizesVal
      this.getUserList()
    },
    // 切换页码的时候会触发，获取当前页码的值
    handleCurrentChange(curPage) {
      this.userQuery.pagenum = curPage
      this.getUserList()
    },
    // 改变状态会触发的函数
    async changeState(info) {
      // 使用模板字符串减少字符串拼接  ${} 内放置的就是变量或者属性值 在内部可以加空格，外部一定不要加
      let { data: res } = await this.$http.put(
        `users/${info.id}/state/${info.mg_state}`
      )
      if (res.meta.status !== 200) {
        // 如果网络原因或者数据库错误，会将状态改变为修改之前的状态，并且提示
        info.mg_state = !info.mg_state
        return this.$message.error('状态更新失败')
      }
      // 修改成功之后的提示
      this.$message.success('状态更新成功')
    },
    dialogClose() {
      this.$refs.addFormRef.resetFields()
    },
    addUser() {
      this.$refs.addFormRef.validate(async valid => {
        // 1.0 如果验证不通过，不会继续往下执行
        if (!valid) return
        // 2.0 发送请求
        let { data: res } = await this.$http.post('users', this.addForm)
        // 3.0 根据 res 的结果返回不同的内容
        if (res.meta.status !== 201) {
          this.$message.error('添加用户失败')
        }
        // 4.0 如果添加成功，提示和关闭窗口即可
        this.$message.success('添加用户成功')
        this.dialogCtrl = false
        // 重新请求数据
        this.getUserList()
      })
    },
    async showDialogEdit(id) {
      // 对应的id获取到这一条用户数据
      let { data: res } = await this.$http.get('users/' + id)
      if (res.meta.status !== 200) return this.$message.error('请求用户数据失败')
      // 将请求回来的数据转存到本地的 data 中
      this.editForm = res.data
      // 打开当前的面板
      this.dialogEdit = true
    },
    resetUserInfo() {
      this.$refs.editFormRef.validate(async valid => {
        // 1.0 如果验证不通过，不会继续往下执行
        if (!valid) return
        // 2.0 发送请求
        let { data: res } = await this.$http.put('users/' + this.editForm.id, {
          email: this.editForm.email,
          mobile: this.editForm.mobile
        })
        // 3.0 根据 res 的结果返回不同的内容
        if (res.meta.status !== 200) {
          this.$message.error('修改用户失败')
        }
        // 4.0 如果添加成功，提示和关闭窗口即可
        this.$message.success('修改用户成功')
        this.dialogEdit = false
        // 重新请求数据
        this.getUserList()
      })
    },
    async delUserInfo(id) {
      let res = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      // 这里代表用户点击的是取消
      if (res !== 'confirm') {
        return this.$message.info('已经取消啦~')
      }
      // 点击了确定按钮
      let { data: res1 } = await this.$http.delete('users/' + id)
      if (res1.meta.status !== 200) return this.$message.error('删除失败')
      this.$message.success('删除成功')
      this.getUserList()
    },
    async setRole(role) {
      this.roleObj = role
      // 发送请求，得到所有的 角色列表
      let { data: res } = await this.$http.get('roles')
      this.roleList = res.data
      this.setRoleDialog = true
    },
    async saveRole(id) {
      if (!this.setRoleId) return this.$message.info('请选择角色')
      let { data: res } = await this.$http.put(`users/${id}/role`, {
        rid: this.setRoleId
      })
      if (res.meta.status !== 200) return this.$message.error('分配角色失败')
      this.$message.success('分配角色成功')
      this.setRoleDialog = false
      this.getUserList()
      // 清空临时存储的对象和选择的角色
      this.setRoleId = ''
      this.roleObj = {}
    }
  }
}
</script>

<style lang='less' scoped>
.el-table {
  margin-top: 20px;
  font-size: 12px;
}
.el-pagination {
  margin-top: 20px;
}
</style>